#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@NAME          : ssl_act.py
@TIME          : 2024/12/23 11:12:00
@AUTHOR        : chenlip
@VERSION       : 0.0.1
@DESCRIPTION   : ssl证书处理程序
    功能：
        1. 读取证书信息（到期时间）
        2. 自动申请腾讯云ssl单域名证书
        3. 自动更新证书到指定服务器上
'''
# --------------------------引用--------------------------
import os, sys, json

import re
import subprocess
from datetime import datetime
import socket
import ssl
# --------------------------引用--------------------------

class SSL_ACT:
    '''
        功能：
        1. 读取证书信息（到期时间）
        2. 自动申请腾讯云ssl单域名证书
        3. 自动更新证书到指定服务器上
    '''
    def __init__(self, domain_name:str='51epub.com'):
        self.domain = domain_name
        pass
    
    @staticmethod
    def get_re_match_result(pattern, string):
        match = re.search(pattern, string)
        return match.group(1)

    @staticmethod
    def parse_time(date_str):
        return datetime.strptime(date_str, "%b %d %H:%M:%S %Y GMT")

    @staticmethod
    def format_time(date_time):
        return datetime.strftime(date_time, "%Y-%m-%d %H:%M:%S")


    def get_cert_info(self):
        """获取证书信息"""
        context = ssl.create_default_context()
        with socket.create_connection((self.domain, 443)) as sock:
            with context.wrap_socket(sock, server_hostname=self.domain) as ssock:
                cert = ssock.getpeercert()
        
        start_date = datetime.strptime(cert['notBefore'], "%b %d %H:%M:%S %Y %Z")
        expire_date = datetime.strptime(cert['notAfter'], "%b %d %H:%M:%S %Y %Z")

        return {
            'start_date': start_date,
            'expire_date': expire_date
        }


    def get_cert_expire_date(self):
        """获取证书剩余时间"""
        info = self.get_cert_info()
        print(info)

        expire_date = info['expire_date']

        # 剩余天数
        return (expire_date - datetime.now()).days


if __name__ == '__main__':
    _domain = '51epub.com'
    ssl_act = SSL_ACT(_domain)
    _d = ssl_act.get_cert_expire_date()
    print(f'证书剩余时间：{_d} 天')
